package priv.zgh.forum.check.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import priv.zgh.forum.auth.entity.User;
import priv.zgh.forum.auth.service.UserService;
import priv.zgh.forum.auth.vo.ResultLoginVo;
import priv.zgh.forum.check.service.EmailService;
import priv.zgh.forum.utils.JwtUtils;
import priv.zgh.forum.utils.R;
import priv.zgh.forum.utils.RandomUtil;

import javax.mail.MessagingException;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/email")
public class EmailController {

    EmailService emailService;
    @Autowired
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }

    UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @ApiOperation("发送邮件")
    @PostMapping("/sendEmail")
    public R sendEmail(@RequestBody HashMap<String,Object> map){
        if(!map.containsKey("email") || map.get("email").equals("")){
            return R.error().message("邮箱地址为空!");
        }else{
            String email = (String) map.get("email");
            // 判断是否有账号是该邮箱
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("email",email);
            if(userService.count(wrapper) > 0){
                // 从redis获取验证码,如果获取就直接返回
                String code = redisTemplate.opsForValue().get(email);
                if(!StringUtils.isEmpty(code)){
                    return R.ok();
                }
                code = RandomUtil.getFourBitRandom();
                emailService.sendEmail(email,"你好,您的验证码为:" + code + ",有五分钟的有效时间,请尽快操作.");
                redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES); // 设置redis数据的生存时间未5分钟
            }else{
                return R.error().message("当前邮箱不存在,请输入正确的邮箱!");
            }
        }
        return R.ok();
    }

    @ApiOperation("检验该邮箱的验证码是否正确")
    @PostMapping("/checkEmailCode")
    public R checkEmailCode(@RequestBody HashMap<String,Object> map){
        if(!map.containsKey("email") || map.get("email").equals("")){
            return R.error().message("邮箱地址为空!");
        }
        if(!map.containsKey("code") || map.get("code").equals("")){
            return R.error().message("验证码为空!");
        }
        String code = (String)map.get("code");
        String email = (String)map.get("email");
        // 从redis中取值
        String temp = redisTemplate.opsForValue().get(email);
        if(temp != null && temp.equals(code)){
            User userInfo = userService.selectUserInfoByEmail(email);
            if(userInfo != null){
                // 返回token
                String token = JwtUtils.createJWT(6000000, userInfo);
                ResultLoginVo resultLoginVo = new ResultLoginVo();
                resultLoginVo.setToken(token);
                resultLoginVo.setUserId(userInfo.getId());
                return R.ok().data("data",resultLoginVo);
            }else {
                return R.error().message("当前拥有该邮箱的用户不存在!");
            }
        }else{
            return R.error().message("当前邮箱验证码不存在或者过期!");
        }
    }

}
